<template>
  <div style="width: 90%; height: 100%; padding: 20px">
    <h2>用户管理</h2>
    <div style="width: 90%; display: flex; justify-content: space-between">
      <el-button @click="dialogFormVisible = true">新增</el-button>
      <div style="display: flex; margin-bottom: 20px">
        <el-input placeholder="请输入内容" v-model="userName"></el-input>
        <el-button type="primary" style="margin-left: 10px" @click="search">搜索</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" title="添加用户" width="500">
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="省份" :label-width="formLabelWidth">
          <el-select v-model="form.selectedProvince" placeholder="选择省份" @change="handleProvinceChange">
            <el-option v-for="province in provinces" :key="province.value" :label="province.label"
              :value="province.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" :label-width="formLabelWidth">
          <el-select v-model="form.selectedCity" placeholder="选择城市">
            <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="form.address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮编" :label-width="formLabelWidth">
          <el-input v-model="form.zip" autocomplete="off" />
        </el-form-item>
        <el-form-item label="日期" :label-width="formLabelWidth">
          <el-date-picker v-model="form.date" type="date" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="add"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogEditFormVisible" title="编辑用户" width="500">
      <el-form :model="editForm">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="editForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="省份" :label-width="formLabelWidth">
          <el-select v-model="editForm.selectedProvince" placeholder="选择省份" @change="handleProvinceChange">
            <el-option v-for="province in provinces" :key="province.value" :label="province.label"
              :value="province.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市" :label-width="formLabelWidth">
          <el-select v-model="editForm.selectedCity" placeholder="选择城市">
            <el-option v-for="city in cities" :key="city.value" :label="city.label" :value="city.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth">
          <el-input v-model="editForm.address" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮编" :label-width="formLabelWidth">
          <el-input v-model="editForm.zip" autocomplete="off" />
        </el-form-item>
        <el-form-item label="日期" :label-width="formLabelWidth">
          <el-date-picker v-model="editForm.date" type="date" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-table :data="tableData" style="width: 90%" border stripe>
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="date" label="日期" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="province" label="省份" width="120" />
      <el-table-column prop="city" label="市区" width="100" />
      <el-table-column prop="address" label="地址" width="200" />
      <el-table-column prop="zip" label="邮编" width="120" />
      <el-table-column fixed="right" label="" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="handleEdit(scope.$index)">编辑</el-button>
          <el-button link type="primary" size="small" @click.prevent="handleDelete(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 90%; display: flex; justify-content: center; align-items: center; height: 80px">
      <el-pagination background layout="prev, pager, next" :total="100" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount } from "vue";
import { regionData, provinceAndCityData, codeToText } from 'element-china-area-data'
import axios from "axios";
import { ElMessage } from "element-plus";

const tableData = ref([])
onBeforeMount(() => {
  axios.get(`/api/user/page?page=1&pageSize=10`).then((res) => {
    console.log(res.data.data.data);
    tableData.value = res.data.data.data
  })
})

const userName = ref("");
const editId = ref(0);

const handleCurrentChange = (c) => {
  axios.get(`/api/user/page?page=${c}&pageSize=10`).then((res) => {
    console.log(res.data.data.data);
    tableData.value = res.data.data.data
  })
}


const provinces = regionData.map(province => ({
  value: province.value,
  label: province.label,
}));

const cities = ref([]);
if (provinces.length > 0) {
  // 获取第一个省份的城市作为初始城市列表
  cities.value = regionData.find(province => province.value === provinces[0].value).children.map(city => ({
    value: city.value,
    label: city.label,
  }));
}
const dialogFormVisible = ref(false);
const dialogEditFormVisible = ref(false);
const formLabelWidth = "140px";
const form = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
  selectedProvince: provinces[0].value,
  selectedCity: cities[0] ? cities[0].value : '',
  date: '',
  address: '',
  zip: ''
});

const editForm = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
  selectedProvince: provinces[0].value,
  selectedCity: cities[0] ? cities[0].value : '',
  date: '',
  address: '',
  zip: ''
});

const handleDelete = (index: number) => {
  console.log(index);
  console.log(tableData.value[index].id)
  axios.delete(`/api/user/${tableData.value[index].id}`).then((res) => {
    axios.get(`/api/user/page?page=1&pageSize=10&name=${userName.value}`).then((res) => {
      console.log(res.data.data.data);
      tableData.value = res.data.data.data
    })
  })
};

const handleEdit = (index: number) => {
  console.log(index);
  let editData = tableData.value[index];
  editId.value = editData.id;
  editForm.name = editData.name;
  editForm.address = editData.address;
  editForm.zip = editData.zip;
  let dateArray = editData.date.split('-');
  editForm.date = new Date(Number(dateArray[0]), Number(dateArray[1])-1, Number(dateArray[2])).toISOString();
  dialogEditFormVisible.value = true;
};

const submitEdit = async () => {
  console.log({
    id: editId.value,
    name: editForm.name,
    date: convertDateString(editForm.date),
    province: codeToText[editForm.selectedProvince],
    city: codeToText[editForm.selectedCity],
    address: editForm.address,
    zip: editForm.zip
  });
  const res = await axios.put('/api/user', {
    id: editId.value,
    name: editForm.name,
    date: convertDateString(editForm.date),
    province: codeToText[editForm.selectedProvince],
    city: codeToText[editForm.selectedCity],
    address: editForm.address,
    zip: editForm.zip
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
  if (res.data.code === 1) {
    dialogEditFormVisible.value = false
    axios.get(`/api/user/page?page=1&pageSize=10`).then((res) => {
      console.log(res.data.data.data);
      tableData.value = res.data.data.data
    })
    window.alert("修改成功");
  } else {
    window.alert("修改失败");
  }
}

const search = () => {
  axios.get(`/api/user/page?page=1&pageSize=10&name=${userName.value}`).then((res) => {
    console.log(res.data.data.data);
    tableData.value = res.data.data.data
  })
}

const handleProvinceChange = (value) => {
  // 根据新的省份值，找到对应的城市数据并更新cities
  const selectedProvinceData = regionData.find(province => province.value === value);
  if (selectedProvinceData) {
    cities.value = selectedProvinceData.children.map(city => ({
      value: city.value,
      label: city.label,
    }));
    // 如果有城市数据，重置城市选择为第一个城市
    if (cities.value.length > 0) {
      form.selectedCity = cities.value[0].name;
    } else {
      form.selectedCity = ''; // 或者设置为一个默认值
    }
  }
}

function convertDateString(dateString) {
  var date = new Date(dateString);
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).slice(-2); // getMonth() returns 0-11, so we add 1
  var day = ("0" + date.getDate()).slice(-2); // for padding zero to single digit date

  return year + "-" + month + "-" + day;
}

const add = async () => {
  console.log({
    name: form.name,
    date: convertDateString(form.date),
    province: codeToText[form.selectedProvince],
    city: codeToText[form.selectedCity],
    address: form.address,
    zip: form.zip
  });
  const res = await axios.post('/api/user', {
    name: form.name,
    date: convertDateString(form.date),
    province: codeToText[form.selectedProvince],
    city: codeToText[form.selectedCity],
    address: form.address,
    zip: form.zip
  }, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
  if (res.data.code === 1) {
    dialogFormVisible.value = false
    axios.get(`/api/user/page?page=1&pageSize=10`).then((res) => {
      console.log(res.data.data.data);
      tableData.value = res.data.data.data
    })
    window.alert("添加成功");
  } else {
    window.alert("添加失败");
  }
}
</script>
